<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button
        type="primary"
        @click="handleAddBanner"
      >添加</a-button>
    </div>

    <s-table
      ref="table"
      :rowKey="(record, index)=> index"
      :columns="columns"
      :data="loadData"
      showPagination="auto"
    >
      <span
        slot="bannerImageUrl"
        slot-scope="src"
      >
        <img
          :src="imageUrlPrefix + src"
          alt="bannerImageUrl"
          width="80"
        />
      </span>
      <span
        slot="action"
        slot-scope="text, record"
      >
        <template>
          <a @click="handleOpenEditBannerModal(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleDeleteBanner(record)">删除</a>
        </template>
      </span>
    </s-table>

    <banner-form-modal ref="bannerFormModal" />
  </a-card>
</template>

<script>
import { STable } from '@/components'
import { getBannerList, deleteBanner, addBanner, updateBanner } from '@/api/config'
import config from '@/config/defaultSettings'
import { BANNER_LIST_COLUMNS } from './constants/banner'
import BannerFormModal from './components/BannerFormModal'

export default {
  name: 'TableListPage',
  components: {
    STable,
    BannerFormModal
  },
  data () {
    return {
      imageUrlPrefix: config.uploadedUrlPrefix,
      columns: BANNER_LIST_COLUMNS,
      loadData: parameter => {
        return getBannerList(Object.assign(parameter))
          .then(res => {
            return res.resData
          })
      }
    }
  },
  methods: {
    handleDeleteBanner (banner) {
      deleteBanner(banner.id).then(res => {
        this.$message.success('删除成功')
        this.$refs.table.refresh()
      })
    },
    handleOpenEditBannerModal (banner) {
      this.$refs.bannerFormModal.show(this.handleActionUpdateBanner, banner)
    },
    handleAddBanner () {
      this.$refs.bannerFormModal.show(this.handleActionAddBanner)
    },
    handleActionAddBanner (banner, callback) {
      addBanner(banner).then(res => {
        callback()
        this.$message.success('添加成功')
        this.$refs.table.refresh()
      }).catch(err => {
        callback(err)
      })
    },
    handleActionUpdateBanner (banner, callback) {
      updateBanner(banner).then(res => {
        callback()
        this.$message.success('编辑成功')
        this.$refs.table.refresh()
      }).catch(err => {
        callback(err)
      })
    }
  }
}
</script>
